package com.mahjong.server.component.logic.handler;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.mahjong.server.common.Common;
import com.mahjong.server.component.logic.main.KHMahjongLogic;
import com.mahjong.server.component.logic.util.LogicConstant;
import com.mahjong.server.manager.OnlineManager;
import com.mahjong.server.mina.protocol.AbsMessageProtocol;
import com.mahjong.server.mina.protocol.DataBuf;
import com.mahjong.server.mina.protocol.MessageProtocol;
import com.mahjong.server.model.Player;

/**
 * 出牌后逻辑判断:是否 吃 碰 杠 胡等
 * @author yougang
 * @date 2013-3-5 上午10:59:26
 * @Description
 */
@Component
@Scope("prototype")
public class LogicReq extends MessageProtocol {

	private static final byte TAG = Common.Req;

	private static final short PROTOCOL_NUM = 0x0103;

	private Logger log = Logger.getLogger(this.getClass());

	KHMahjongLogic logic = new KHMahjongLogic();
	
	@Autowired
	private OnlineManager onlineManager;
	
	//客户端传递两个参数
	private int playerId;
	private String pai;

	@Override
	public short getProtocolNum() {
		return PROTOCOL_NUM;
	}

	@Override
	public byte getTag() {
		return TAG;
	}

	/**
	 * 执行的动作 0无动作 1吃 2碰 3杠 3胡
	 * 同时满足多个动作用,隔开
	 */
	public AbsMessageProtocol execute(IoSession session, AbsMessageProtocol req) {
		log.debug(this.getClass().getSimpleName() + " execute");
		String actions = "";
		try {
			if (playerId <0 || pai == null) {
				Player player = onlineManager.getPlayerById(playerId);
				String[] pais = player.getMahjongData().getShouZhong();
				boolean isChi = logic.isChi(pai, pais);
				boolean isPeng = logic.isPeng(pai, pais);
				boolean isGang = logic.isGang(pai, pais);
				boolean isHuPai = logic.isHuPai(pai, pais);
				if (isChi) {
					actions += LogicConstant.CHI_ACTION+",";
				}
				if (isPeng) {
					actions += LogicConstant.PENG_ACTION+",";
				}
				if (isGang) {
					actions += LogicConstant.GANG_ACTION+",";
				}
				if (isHuPai) {
					actions += LogicConstant.HU_ACTION+",";
				}
				if (actions.equals("")) {
					actions += "0,";
				}
				return new LogicResp(actions.substring(0,actions.length()-1));
			} else {
				return new LogicResp("-1");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void reqDecode(DataBuf buf) {
		log.debug(this.getClass().getSimpleName() + " decode");
		playerId = buf.getInt();
		pai = buf.getString();
	}
}
